<?php

/**
 * 历史数据的处理
 * 更新指定员工 一定请假记录重新生成  file.php update uid leave_id
*/
apf_require_class('Oa_Job_Attendance_Abstract');
apf_require_class("Tools_Tools");

apf_require_class('Const_LeaveType');
apf_require_class('Bll_Attendance_DailyReport');
apf_require_class('Bll_Attendance_DailyLeave');
apf_require_class('Bll_Attendance_AccessDayRecord');

class Oa_Job_Attendance_SetOneUser extends Oa_Job_Attendance_Abstract {
    /** 考勤系统读 **/
    private $readdb = "attendance_slave";
    /** 考勤系统写 **/
    private $writedb = "attendance_master";


    public function run($params){
        $type = $params['type'];
        $uid = $params['uid'];
        $start = $params['start'];
        $end = $params['end'];
        if(empty($type)){
            $this->log('Not run Type');exit;
        }
        if($type=='init'){
            $this->init_user_data($uid,$start,$end);
        }elseif($type=='update'){//更新一个用户的指定请假 update uid  leave_id
            $this->update_user_data($uid,$start);
        }elseif($type=="reset_leave"){//reset_leave 0 leave_id1 leave_id2
            $this->reset_leave_data($start,$end);
        }
        $this->log('Clear Over');
    }
    /**
     * 恢复一段请假记录的数据入库
     * @param int $start 请假记录id
     * @param int $end 请假记录id
     */
    private function reset_leave_data($start,$end){
        $sql_gc = "SELECT * FROM leave_record WHERE id>=$start AND id<=$end";
        $datalist=$this->get_rows($sql_gc,array(),false,$this->writedb);
        if(empty($datalist)){
            $this->log('Not Found reset leave data.');exit;
        }
        foreach($datalist as $val){
            $this->update_user_data($val['user_id'],$val['id']);
            $this->log("Leave Id:".$val['id']." clear");
        }
    }

    /**
     * 修改用户所有请假记录的信息
     * @param unknown_type $uid
     */
    private function update_user_data($uid,$leave_id){
        $this->log("Update $uid From ID:$leave_id");
        $userinfo = $this->get_one_user($uid);
        if(empty($userinfo)){
            $this->log('Not Found User');exit;
        }
        $xk_bll = new Bll_Attendance_DailyLeave();
        $daily_bll = new Bll_Attendance_DailyReport();

        $leave_data=$daily_bll->get_leave_record_by_id($leave_id);
        if(empty($leave_data) || $uid!=$leave_data['user_id']){
            $this->log('Not Found Leave Data by id='.$leave_id);exit;
        }
        //print_r($leave_data);
        $etxt = date('Y-m-d H:i',$leave_data['start_time']).'==='.date('Y-m-d H:i',$leave_data['end_time']);

        $daylist = $daily_bll->format_leave_days($leave_data['start_time'],$leave_data['end_time'],$leave_data['type']);
        if(empty($daylist)){
            $this->log('请假日期格化式失败='.$etxt);exit;
        }
        //先清空和这次相关的每日状态
        foreach ($daylist as $day=>$val){
            //根据打卡记录重新生成上下考勤状态
            $status = $daily_bll->get_one_accessday($uid,$day);
            $is_later =$status['status'][0]==1 ? 1:0;
            $insert_data = array(
                    'user_id'        => $uid,
                    'dateline'       => $day,
                    'days'           => 0,
                    'am_status'      => $status['status'][0],
                    'am_type'        => 0,
                    'am_leave_status'=> 0,
                    'pm_status'      => $status['status'][1],
                    'pm_type'        => 0,
                    'pm_leave_status'=> 0,
                    'is_later'       => $is_later,
                    'leave_early'    => 0,
            );
            //print_r($insert_data);exit;
            $xk_bll->get_kq_dao()->update($insert_data,array('user_id'=>$uid,'dateline'=>$day));
            $sql = " AND dateline=$day";
            //先清空原有的请假记录
            $user_last = "delete from user_last_leave_record where user_id=$uid $sql";
            $this->execute( $user_last,array(), $this->writedb);

            $user_daily = "delete from user_leave_daily where user_id=$uid $sql";
            $this->execute( $user_daily,array(), $this->writedb);

            $user_curr = "delete from user_leave_record_ext  where user_id=$uid $sql";
            $this->execute( $user_curr,array(), $this->writedb);
        }

        $type=$leave_data['type'];
        var_dump($type);
        var_dump(Const_LeaveType::LEAVE_TYPE_GONGCHU);
        //存入请假记录
        switch ($type){
            case Const_LeaveType::LEAVE_TYPE_CHIDAO:
                $daily_bll->update_come_late($leave_data,100);
                break;
            case Const_LeaveType::LEAVE_TYPE_ZAOTUI:
                $daily_bll->update_left_early($leave_data,100);
                break;
            case Const_LeaveType::LEAVE_TYPE_GONGCHU:
                $daily_bll->update_business_travel($leave_data,100);
                break;
            case Const_LeaveType::LEAVE_TYPE_CHUCHA:
                $daily_bll->update_business_trip($leave_data, 100);
                break;
            default:
                $daily_bll->update_common_leave($leave_data,100);
                break;
        }
        $this->log("End $uid From $start----$end");
    }
    private function init_user_data($uid,$start,$end){
        $this->log('[[[Start Init User Data');
        $xk_bll = new Bll_Attendance_DailyLeave();
        $daily_bll = new Bll_Attendance_DailyReport();

        $userinfo = $this->get_one_user($uid);
        if(empty($userinfo)){
            $this->log('Not Found User');exit;
        }
        $end_date = intval(str_replace('-','',substr($userinfo['enter_date'],0,10)));//入职时间
        $dimission_date = intval(str_replace('-','',substr($userinfo['dimission_date'],0,10)));//入职时间
        if($dimission_date && $dimission_date < $start){
            $this->log('dimission_date > '.$start);exit;
        }

        //clear old
        $this->clear_old_data($uid,$start,$end);

        $startx= strtotime($start);
        $endx = strtotime($end);
        for($i=$startx;$i<=$endx;$i+=86400){
            $k = date('Ymd',$i);
            if($k <$end_date){//小于入职时间的不算
                continue;
            }
            if($dimission_date && $k >$dimission_date){//大于离职时间的不算
                continue;
            }
            $status = $daily_bll->get_one_accessday($uid,$k);
            $is_later =$status['status'][0]==1 ? 1:0;
            $insert_data = array(
                    'user_id'        => $uid,
                    'dateline'       => $k,
                    'days'           => 0,
                    'am_status'      => $status['status'][0],
                    'am_type'        => 0,
                    'am_leave_status'=> 0,
                    'pm_status'      => $status['status'][1],
                    'pm_type'        => 0,
                    'pm_leave_status'=> 0,
                    'is_later'       => $is_later,
                    'leave_early'    => 0,
            );
            $xk_bll->get_kq_dao()->insert($insert_data);
        }
        $this->insert_user_leave_data($uid,$daily_bll);
        $this->log('Init User Data Success!');
    }
    private function insert_user_leave_data($uid,$daily_bll){
        $start = 0;
        while (true){
            $sql_gc = "SELECT * FROM leave_record WHERE user_id=$uid AND  id>$start AND end_time>'2012-06-30 00:00:00' limit 5";
            $datalist=$this->get_rows($sql_gc,array(),false,$this->writedb);
            //print_r($datalist);exit;
            if(empty($datalist)) {
                break;
            }

            foreach ($datalist as $leave_data) {
                $this->log($leave_data['type'].'=='.$leave_data['start_time'].'=='.$leave_data['end_time']);
                $leave_data['start_time'] = strtotime($leave_data['start_time']);
                $leave_data['end_time'] = strtotime($leave_data['end_time']);
                $leave_data['type'] = $daily_bll->format_leave_type($leave_data['type']);
                $leave_data['status']=$daily_bll->format_leave_status($leave_data['status']);
                $leave_data['daylist']=$daily_bll->format_leave_days($leave_data['start_time'],$leave_data['end_time'],$leave_data['type']);
                $type=$leave_data['type'];

                switch ($type){
                    case Const_LeaveType::LEAVE_TYPE_CHIDAO:
                        $daily_bll->update_come_late($leave_data,100);
                        break;
                    case Const_LeaveType::LEAVE_TYPE_ZAOTUI:
                        $daily_bll->update_left_early($leave_data,100);
                        break;
                    case Const_LeaveType::LEAVE_TYPE_GONGCHU:
                        $daily_bll->update_business_travel($leave_data,100);
                        break;
                    case Const_LeaveType::LEAVE_TYPE_CHUCHA:
                        $daily_bll->update_business_trip($leave_data, 100);
                        break;
                    default:
                        $daily_bll->update_common_leave($leave_data,100);
                        break;
                }
            }//exit;
            $num = count($datalist);
            $start = $datalist[$num-1]['id'];
            unset($datalist);
        }
    }
    private function clear_old_data($uid,$start,$end){
        $user_days = "delete from user_day_status where user_id=$uid";
        $this->execute( $user_days,array(), $this->writedb);

        $user_last = "delete from user_last_leave_record where user_id=$uid";
        $this->execute( $user_last,array(), $this->writedb);

        $user_daily = "delete from user_leave_daily where user_id=$uid";
        $this->execute( $user_daily,array(), $this->writedb);

        $user_curr = "delete from user_leave_record_ext  where user_id=$uid";
        $this->execute( $user_curr,array(), $this->writedb);
    }

    private function get_one_user($uid) {
        $sql = "SELECT user_id FROM user_info WHERE user_id=$uid";
        return $this->get_db_row($sql,$this->writedb,array());
    }
}